import React from "react";
import testData from "../resourceManage/testData";
import { Button, DatePicker, Form, Input, InputNumber, message, Modal, Radio, Select, Table } from "antd";
import { chargingDetailAdd, chargingDetailDelete, chargingDetailInfo, chargingDetailList, chargingDetailUpdate, combinationList, discountList, packageList, packageListByCombinationId } from "@/services/chargingManage";
import moment from "moment";

class DetailList extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      current:1,
      size:10,
      loading:false,
      total:0,
      list:[],
      selectedRowKeys:[],
      visible:false,
      packageOptions:[],
      discountOptions:[],
      detailId:null,
      combinationOptions:[]
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  getList = () => {
    this.setState({
      loading:true
    },async () => {
      const { current,size } = this.state;
      const { caseId } = this.props
      const res = await chargingDetailList({current,size,planId:caseId})
      this.setState({
        list:res.records,
        total:res.total,
        loading:false,
        selectedRowKeys:[]
      })
    })
  }

  doSearch = (current,size) => {
    this.setState({current,size},() => {
      this.getList()
    })
  }

  onSelectChange = selectedRowKeys => {
    this.setState({selectedRowKeys})
  }

  removeConfirm = () => {
    Modal.confirm({
      title:"是否确定删除？",
      okText:"确定",
      cancelText:"取消",
      okType:"danger",
      onOk:() => {
        this.doRemove()
      }
    })
    
  }

  doRemove = async () => {
    const res = await chargingDetailDelete({ids:this.state.selectedRowKeys})
    message.info(res.message)
    this.getList()
    this.props.refreshCaseInfo()
  }

  closeVisible = () => {
    this.props.form.resetFields()
    this.setState({
      visible:false
    })
  }

  okValidate = () => {
    this.props.form.validateFields((error,values) => {
      if(!error){
        const { caseId } = this.props
        let obj = {
          planId:caseId,
          useId:values.useId,
          settlementId:values.settlementId,
          packageId:values.packageId,
          discountId:values.discountId,
          startDate:values.startDate ? moment(values.startDate).format("YYYY-MM-DD") : '',
          endDate:values.endDate ? moment(values.endDate).format("YYYY-MM-DD") : '',
          periodType:values.periodType,
          name:values.name,
          packageType:values.packageType,
          combinationId:values.combinationId
        }
        if(!values.discountId){
          obj.discount = !values.price && !values.rate ? null : {
            price:values.price,
            rate:values.rate,
            name:values.discountNewName
          }
        }

        this.doSave(obj)
      }
    })
  }

  doSave = async obj => {
    let res = {}
    if(this.state.detailId){
      obj.id = this.state.detailId
      res = await chargingDetailUpdate(obj)
    }else{
      res = await chargingDetailAdd(obj)
    }
    if(res.code == -1){
      return false
    }
    message.info(res.message)
    this.closeVisible()
    this.getList()
    this.props.refreshCaseInfo()
  }

  openDetail = id => {
    this.setState({
      visible:true,
      detailId:id
    },() => {
      if(id){
        this.getDetailInfo()
      }
    })
  }

  getDetailInfo = async () => {
    const res = await chargingDetailInfo({id:this.state.detailId})
    const { form:{setFieldsValue} } = this.props;
    setFieldsValue({
      useId:res.useId,
      settlementId:res.settlementId,
      packageId:res.packageId,
      startDate:res.startDate ? moment(res.startDate) : '',
      endDate:res.endDate ? moment(res.endDate) : '',
      discountId:res.discountId,
      caseType:0,
      periodType:res.periodType,
      name:res.name,
      packageType:res.packageType
    })
    if(res.packageType == 1){
      setFieldsValue({combinationId:res.combinationId})
      this.getPackageOptions(1)
      this.getPackageOptions(2,res.combinationId)
    }else{
      this.getPackageOptions(0)
    }
    if(res.settlementId){
      this.getDiscountList(res.settlementId)
    }
    
  }

  disabledEndDate = endValue => {
    const startValue = this.props.form.getFieldValue("startDate")
    
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  };

  renderPackagePrice = packageId => {
    let price = 0
    for(const item of this.state.packageOptions){
      if(item.id == packageId){
        price = item.price
      }
    }

    return price
  }

  getDiscountList = async value => {
    const res = await discountList({current:1,size:999,settlementId:value})
    this.setState({discountOptions:res.records.filter(item => item.isExpired == 0)})
  }

  renderDiscountInfo = (discountId,packagePrice) => {
    const { discountOptions } = this.state;
    let discountType = 0
    let price = 0
    let rate = 0
    let totalValue = 0
    for(const item of discountOptions){
      if(item.id == discountId){
        discountType =  item.price !== '' && item.price !== null && item.price !== undefined ? 0 : 1
        price = item.price
        rate = item.rate
      }
    }
    if(discountType == 0){
      totalValue = packagePrice - price
    }else{
      totalValue = packagePrice * (1 - (rate / 100))
    }
    return (
      <div>
        <Form.Item label="折扣类型">
          <Radio.Group value={discountType} disabled>
            <Radio value={0}>折扣金额</Radio>
            <Radio value={1}>折扣率</Radio>
          </Radio.Group>
        </Form.Item>
        {
          discountType == 0 ? (
            <Form.Item label="折扣金额">
              <InputNumber value={price} disabled  precision={2} />
              <span>元</span>
            </Form.Item>
          ) : (
            <Form.Item label="折扣率">
              <InputNumber value={rate} disabled max={100} />
              %
            </Form.Item>
          )
        }
        <Form.Item label="成交金额">
          <InputNumber disabled value={totalValue} precision={2} />
          <span>元</span>
        </Form.Item>
      </div>
    )
  }

  mathTotalPrice = (packagePrice,formValue) => {
    let totalValue = 0
    if(formValue.discountType == 0){
      totalValue = packagePrice - formValue.price
    }else{
      totalValue = packagePrice * (1 - (formValue.rate / 100))
    }
    
    return totalValue
  }

  changeSettlementId = value => {
    this.getDiscountList(value)
  }

  changePackageType = value => {
    this.props.form.setFieldsValue({packageId:'',combinationId:""})
    this.setState({
      packageOptions:[]
    },() => {
      this.getPackageOptions(value)
    })
    
  }

  changeCombinationId = value => {
    this.props.form.setFieldsValue({packageId:''})
    this.setState({
      packageOptions:[]
    },() => {
      this.getPackageOptions(2,value)
    })
  }

  getPackageOptions = async (flag,combinationId) => {
    let res = {records:[]}
    if(flag == 0){
      res = await packageList({current:1,size:999,search:""})
      this.setState({
        packageOptions:res.records.filter(item => item.isExpired == 0)
      })
    }else if(flag == 1){
      res = await combinationList({current:1,size:999,search:""})
      this.setState({
        combinationOptions:res.records
      })
    }else if(flag == 2){
      //根据套餐组合id获取套餐列表
      res = await packageListByCombinationId({id:combinationId})
      this.setState({
        packageOptions:res.filter(item => item.isExpired == 0)
      })
    }
  }

  render(){
    const { current,size,list,loading,total,selectedRowKeys,visible,packageOptions,discountOptions,combinationOptions } = this.state;
    const { form:{getFieldDecorator,getFieldValue,setFieldsValue,resetFields,getFieldsValue},caseId,caseInfo,useList,settlementList,packageName,readonly } = this.props;
    const formItemLayout = {
      labelCol: { span: 2 },
      wrapperCol: { span: 10 },
    };
    const columns = [
      {
        title:"行序号",
        dataIndex:"index",
        width:80,
        render:(text,row,index) => {
          return (current - 1) * size + (index + 1)
        }
      },
      {
        title:"明细名称",
        dataIndex:"name",
        width:100
      },
      {
        title:"签约方",
        dataIndex:"signName",
        width:100,
        render:() => {
          return caseInfo.signName
        }
      },
      {
        title:"套餐组合",
        dataIndex:"packageType",
        width:100,
        render:type => {
          return type == 0 ? '单套餐' : type == 1 ? '套餐组' : ''
        }
      },
      {
        title:"使用方",
        dataIndex:"useName",
        width:100
      },
      {
        title:"使用套餐",
        dataIndex:"packageName",
        width:100
      },
      {
        title:"结算方",
        dataIndex:"settlementName",
        width:100
      },
      {
        title:"付款条款",
        dataIndex:"paymentProvision",
        width:100,
        render:() => {
         return caseInfo.paymentProvision
        }
      },
      {
        title:"付费周期",
        dataIndex:"periodType",
        width:100,
        render:type => {
          return type == 0 ? '月' : type == 1 ? '年' : ''
        }
      },
      {
        title:"折扣方案",
        dataIndex:"discountName",
        width:100
      },
      {
        title:"成交金额",
        dataIndex:"realPrice",
        width:100
      },
      {
        title:"应用计费开始日期",
        dataIndex:"startDate",
        width:100,
        render:time => {
          return time ? moment(time).format("YYYY-MM-DD") : ''
        }
      },
      {
        title:"应用计费停止日期",
        dataIndex:"endDate",
        width:100,
        render:time => {
          return time ? moment(time).format("YYYY-MM-DD") : ''
        }
      },
      {
        title:"操作",
        width:120,
        fixed:"right",
        render:(text,row) =>  {
          return (
            <div>
              <Button type={readonly ? '' : "primary"} style={{marginRight:8}} size="small" onClick={() => this.openDetail(row.id)}>{readonly ? '查看' : '编辑'}</Button>
            </div>
          )
        }
      }
    ]

    return (
      <div style={visible ? {maxHeight:"calc(100vh - 500px)",overflowY:"auto"} : {}}>
        {
          visible ? (
            <div>
              <Form className="normalForm" {...formItemLayout}>
                <Form.Item label="明细名称">
                  {getFieldDecorator("name",{rules:[{required:true,message:"请输入"}]})(
                    <Input />
                  )}
                </Form.Item>
                <Form.Item label="签约方">
                  <Input disabled value={caseInfo.signName} />
                </Form.Item>
                <Form.Item label="使用方">
                  {getFieldDecorator("useId")(
                    <Select showSearch optionFilterProp="children" disabled={readonly}>
                      {useList.map(item => <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>)}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item label="套餐组合">
                  {getFieldDecorator("packageType",{rules:[{required:true,message:"请选择"}]})(
                    <Select onChange={this.changePackageType} disabled={readonly}>
                      <Select.Option value={1}>套餐组</Select.Option>
                      <Select.Option value={0}>单套餐</Select.Option>
                    </Select>
                  )}
                </Form.Item>
                {
                  getFieldValue("packageType") == 1 ? (
                    <Form.Item label="套餐组">
                      {getFieldDecorator("combinationId",{rules:[{required:true,message:"请选择"}]})(
                        <Select showSearch optionFilterProp="children" disabled={readonly} onChange={this.changeCombinationId}>
                          {combinationOptions.map(item => <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>)}
                        </Select>
                      )}
                    </Form.Item>
                  ) : ''
                }
                
                <Form.Item label="签约套餐">
                  {getFieldDecorator("packageId",{rules:[{required:true,message:"请选择"}]})(
                    <Select disabled={readonly} showSearch optionFilterProp="children" >
                      {packageOptions.map(item => <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>)}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item label="结算方">
                  {getFieldDecorator("settlementId",{rules:[{required:true,message:"请选择"}]})(
                    <Select disabled={readonly} onChange={this.changeSettlementId} showSearch optionFilterProp="children" >
                      {settlementList.map(item => <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>)}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item label="付款条款">
                  <Input disabled value={caseInfo.paymentProvision} />
                </Form.Item>
                <Form.Item label="付费周期">
                  {getFieldDecorator("periodType",{rules:[{required:true}]})(
                    <Select disabled={readonly}>
                      <Select.Option value={0}>月</Select.Option>
                      <Select.Option value={1}>年</Select.Option>
                    </Select>
                  )}
                </Form.Item>
                <Form.Item label="套餐金额">
                  <Input disabled value={this.renderPackagePrice(getFieldValue("packageId"))} />
                </Form.Item>
                <Form.Item label="折扣方案">
                  {getFieldDecorator("caseType",{initialValue:0})(
                    <Radio.Group disabled={readonly}>
                      <Radio value={0}>已有折扣方案</Radio>
                      <Radio value={1}>生成折扣方案</Radio>
                    </Radio.Group>
                  )}
                  {
                    getFieldValue("caseType") == 0 ? (
                      <Form.Item style={{marginBottom:0}}>
                        {getFieldDecorator("discountId")(
                          <Select disabled={readonly}>
                            {discountOptions.map(item => <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>)}
                          </Select>
                        )}
                      </Form.Item>
                    ) : ''
                  }
                </Form.Item>
                {
                  getFieldValue("caseType") == 0 ? (
                    this.renderDiscountInfo(getFieldValue("discountId"),this.renderPackagePrice(getFieldValue("packageId")))
                  ) : (
                    <div>
                      <Form.Item label="折扣类型">
                        {getFieldDecorator("discountType",{initialValue:0})(
                          <Radio.Group disabled={readonly}>
                            <Radio value={0}>折扣金额</Radio>
                            <Radio value={1}>折扣率</Radio>
                          </Radio.Group>
                        )}
                      </Form.Item>
                      <Form.Item label="折扣名称">
                        {getFieldDecorator("discountNewName",{rules:[{required:true,message:"请输入"}]})(
                          <Input />
                        )}
                      </Form.Item>
                      {
                        getFieldValue("discountType") == 0 ? (
                          <Form.Item label="折扣金额">
                            {getFieldDecorator("price")(
                              <InputNumber disabled={readonly} precision={2} />
                            )}
                            <span>元</span>
                          </Form.Item>
                        ) : (
                          <Form.Item label="折扣率">
                            {getFieldDecorator("rate")(
                              <InputNumber disabled={readonly} max={100} precision={2} />
                            )}
                            %
                          </Form.Item>
                        )
                      }
                      <Form.Item label="成交金额">
                        <InputNumber precision={2} disabled value={this.mathTotalPrice(this.renderPackagePrice(getFieldValue("packageId")),getFieldsValue())} />
                        <span>元</span>
                      </Form.Item>
                    </div>
                  )
                }
                
                <Form.Item label="应用计费开始日期">
                  {getFieldDecorator("startDate",{rules:[{required:true,message:"请选择"}]})(
                    <DatePicker disabled={readonly} onChange={() => resetFields(["endDate"])} />
                  )}
                </Form.Item>
                <Form.Item label="应用计费停止日期">
                  {getFieldDecorator("endDate",{rules:[{required:true,message:"请选择"}]})(
                    <DatePicker disabled={!getFieldValue("startDate") || readonly} disabledDate={this.disabledEndDate} />
                  )}
                </Form.Item>
                <Form.Item label=" " colon={false}>
                  <Button onClick={this.closeVisible} style={{ marginRight: 8 }}>取消</Button>
                  {
                    readonly ? '' : <Button onClick={this.okValidate} type="primary">保存</Button>
                  }
                </Form.Item>
              </Form>
            </div>
          ) : (
            <div>
              <div style={{marginBottom:24}}>
                <Button disabled={!caseId || readonly} type="primary" icon="plus" style={{marginRight:8}} onClick={() => this.openDetail()}>增加明细</Button>
                
                <Button type="danger" onClick={this.removeConfirm} disabled={selectedRowKeys.length == 0 || readonly}>删除</Button>
              </div>

              <Table 
                columns={columns}
                dataSource={list}
                loading={loading}
                rowKey={'id'}
                scroll={{x:"auto",y:"calc(100vh - 700px)"}}
                pagination={{
                  current,
                  pageSize:size,
                  showQuickJumper:true,
                  onChange:this.doSearch,
                  total
                }}
                rowSelection={{
                  selectedRowKeys,
                  onChange: this.onSelectChange
                }}
              />
            </div>
          )
        }
        
        
      </div>
    )
  }
}

export default Form.create()(DetailList)